<template>
  <div id="login" class="login-container">
    <van-icon  style="margin-left: -350px" name="arrow-left" @click="goBack" />

    <van-nav-bar title="登录" />


    <van-form @submit="handleLogin" ref="form">
      <van-field
          v-model="form.username"
          label="用户名"
          required
          placeholder="请输入用户名"
      />
      <van-field
          v-model="form.password"
          label="密码"
          type="password"
          required
          placeholder="请输入密码"
      />
      <van-button type="info" native-type="submit" :loading="loading">登录</van-button>
    </van-form>
    <van-toast v-if="message" :type="messageType">{{ message }}</van-toast>
  </div>
</template>

<script>
import axios from 'axios'; // 引入 axios

export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      loading: false,
      message: '',
      messageType: ''
    };
  },
  methods: {
    goBack() {
      this.$router.go(-1); // 返回上一页
    },
    async handleLogin() {
      // 前端验证
      if (!this.form.username) {
        this.$toast.fail('用户名不能为空')
        return;
      }
      if (!this.form.password) {
        this.$toast.fail('密码不能为空') // 修改提示信息
        return;
      }

      this.loading = true;
      this.message = '';

      try {
        // 发送登录请求
        const response = await axios.post(`http://localhost:9999/api-user/user/login1`, null, {
          params: {
            username: this.form.username,
            password: this.form.password
          }
        });

        const result = response.data;

        if (result.code === 1) { // 检查返回的 code
          let user =result.data;
          // alert(JSON.stringify(user))
          if (user.length>0){
            let userData=user[0];
            // alert(JSON.stringify(userData))
            // let phone=JSON.stringify(userData.userphone)
            let id=JSON.stringify(userData.id);
            // alert(phone)
            this.$toast.success(result.message)
            localStorage.setItem("user",JSON.stringify(userData));
            this.$router.push('/mine');

          }

        } else {
          this.message = "登录失败：" + result.message;
          this.messageType = "error";
          this.$toast.fail(result.message)
        }
      } catch (error) {
        console.error("请求失败: ", error);
        this.message = "请求失败";
        this.messageType = "error";
        this.$toast.fail(error.message || '请求失败') // 修改错误提示
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>

.login-container {
  padding: 16px;
}
</style>